package com.my.interceptor;

import java.util.Locale;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.support.RequestContext;

import com.my.filter.XssHttpServletRequestWrapper;

public class LocalLanguageInterceptor implements HandlerInterceptor {
	private static final Logger logger = LoggerFactory.getLogger(LocalLanguageInterceptor.class);

	/**
	 * Controller处理之前进行调用
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		Cookie[] cookies = request.getCookies();// 取cookie值，这里还有其他网站的
		String cookieValue = null;
		Locale locale = new Locale("zh", "CN");
		
		if (cookies != null) {
			// 下面是找到本项目的cookie
			for (int i = 0; i < cookies.length; i++) {
				if ("lang".equals(
						cookies[i].getName())) {
					cookieValue = cookies[i].getValue();
					break;
				}
			}
			if(null!=cookieValue && cookieValue.equals("en_US")){
				locale = new Locale("en", "US"); 
			}
		}
		
		request.getSession().setAttribute(
				SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
		return true;
	}

	/**
	 * Controller的方法调用之后执行
	 */
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	/**
	 * DispatcherServlet渲染了视图执行
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
